/**
 * 
 */
package com.feib.stms.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.feib.stms.dao.GroupDao;
import com.feib.stms.dao.MenuItemDao;
import com.feib.stms.dao.RoleDao;
import com.feib.stms.dao.UserDao;
import com.feib.stms.dao.jdbc.ConfirmRuleJdbcDao;
import com.feib.stms.dao.jdbc.SecuritiesJdbcDao;
import com.feib.stms.model.ConfirmRule;
import com.feib.stms.model.Group;
import com.feib.stms.model.MenuItem;
import com.feib.stms.model.Role;
import com.feib.stms.model.Securities;
import com.feib.stms.model.User;
import com.feib.stms.pagination.PaginatedList;
import com.feib.stms.service.GroupService;
import com.feib.stms.util.UserUtil;

/**
 * @author Lion Gao
 *
 */
@Service("groupService")
public class GroupServiceImpl extends BaseServiceImpl implements GroupService 
{
	/**
	 * 
	 */
	private static final long serialVersionUID = -1680061367855602158L;

	@Resource(name="groupDao")
    private GroupDao groupDao;
	
	@Resource(name="securitiesDao")
	private SecuritiesJdbcDao securitiesDao;
	
	@Resource(name="confirmRuleDao")
	private ConfirmRuleJdbcDao confirmRuleDao;
	
	@Resource(name="userDao")
    private UserDao userDao;

    @Resource(name="roleDao")
    private RoleDao roleDao;
    
    @Resource(name="menuItemDao")
    private MenuItemDao menuItemDao;
	/*
	 * (non-Javadoc)
	 * @see com.feib.stms.service.GroupService#findForPaginatedListByGroup(com.feib.stms.model.Group, com.feib.stms.pagination.PaginatedList)
	 */
	public PaginatedList<Group> findForPaginatedListByGroup(Group group, PaginatedList<Group> paginatedList) {
		return groupDao.queryForPaginatedListByGroup(group, paginatedList);
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.feib.stms.service.GroupService#getByGroupPk(java.lang.Long)
	 */
	public Group getByGroupPk(Long groupPk) {
		return groupDao.getByGroupPk(groupPk);
	}

	/*
	 * (non-Javadoc)
	 * @see com.feib.stms.service.GroupService#saveGroup(com.feib.stms.model.Group)
	 */
	public int saveGroup(Group group) {
		if(group != null){
			String userId = UserUtil.getUserId();
			group.setCreatedBy(group.getGroupNo() + "_" +userId);
			group.setCreatedDate(new Date());
			group.setUpdatedBy(group.getGroupNo() + "_" + userId);
			group.setUpdatedDate(new Date());
		}
		//新增券商
		int insertCount = groupDao.insert(group);
        
		//新增券商同時，新增一筆分公司資料
		Securities securities = new Securities();
		securities.setGroup(group);
		securities.setParentSecurities(null);
		securities.setSecuritiesNo(group.getGroupNo());
		securities.setSecuritiesName(group.getGroupName());
		securities.setSecuritiesAddress(group.getGroupAddress());
		securities.setContactName(group.getContactName());
		securities.setContactEmail(group.getContactEmail());
		securities.setContactTelno(group.getContactTelno());
		securities.setContactCellno(group.getContactCellno());
		securities.setSecuritiesNote(group.getGroupNote());
		securities.setUbm(group.getUbm());
		securities.setCreatedBy(group.getCreatedBy());
		securities.setCreatedDate(group.getCreatedDate());
		securities.setUpdatedBy(group.getUpdatedBy());
		securities.setUpdatedDate(group.getUpdatedDate());
		int insertCount2 = 0;
		if(insertCount > 0){
			insertCount2 = securitiesDao.insert(securities);
		}
		
		//獲取登陸者
    	User user = UserUtil.getUser();
		//新增兩個預設使用者admin1和admin2
		Securities tempSecurities = securitiesDao.findSecuritiesPkBySecurities(securities);
		if(null != tempSecurities){
			//新增ADMIN1   帳號
	        User user1 = new User();
	        user1.setGroup(group);
	        user1.setSecurities(tempSecurities);
	        user1.setUserId("admin1");
	        user1.setUserPwd("4a7d1ed414474e4033ac29ccb8653d9b"); //default pwd: 0000
	        user1.setUserName("系統管理者");
	        user1.setUserEmail(group.getContactEmail());
	        user1.setUserPhoneNo(group.getContactTelno());
	        if (null == user1.getUserPhoneNo())
	        	user1.setUserPhoneNo(group.getContactCellno());
	        user1.setEnabled(Boolean.TRUE);
	        user1.setLocked(Boolean.FALSE);
	        user1.setPwdExpiredDate(new Date()); // 強迫下次登入要變更密碼
	        user1.setCreatedBy(group.getGroupNo() + "_" + user.getUserId());//操作者
	        user1.setCreatedDate(new Date());//操作日期
	        
	        //新增ADMIN2 帳號
	        User user2 = new User();
	        user2.setGroup(group);
	        user2.setSecurities(tempSecurities);
	        user2.setUserId("admin2");
	        user2.setUserPwd("4a7d1ed414474e4033ac29ccb8653d9b"); //default pwd: 0000
	        user2.setUserName("系統管理者");
	        user2.setUserEmail(group.getContactEmail());
	        user2.setUserPhoneNo(group.getContactTelno());
	        if (null == user2.getUserPhoneNo())
	        	user2.setUserPhoneNo(group.getContactCellno());
	        user2.setEnabled(Boolean.TRUE);
	        user2.setLocked(Boolean.FALSE);
	        user2.setPwdExpiredDate(new Date()); // 強迫下次登入要變更密碼
	        user2.setCreatedBy(group.getGroupNo() + "_" + user.getUserId());//操作者
	        user2.setCreatedDate(new Date());//操作日期
	        
	        //新增 ADMINISTRATOR Role
	        Role role = new Role();
	        role.setGroup(group);
	        role.setRoleNo("ADMINISTRATOR");
	        role.setRoleName("系統群組");
	        role.setUsers(new HashSet<User>());
	        //將user1 和 user2 加入新建立的role中
	        role.getUsers().add(user1);
	        role.getUsers().add(user2);
	        
	        role.setMenuItems(new HashSet<MenuItem>());
	        List<MenuItem> adminMenuItems = menuItemDao.getSecuritiesMenuItem();
	        List<String> menuItemPk = new ArrayList<String>();
	        for (MenuItem adminMenuItem : adminMenuItems)
	        {
	            role.getMenuItems().add(adminMenuItem);
	            menuItemPk.add(adminMenuItem.getMenuItemPk().toString());
	        }
	        //新增role
	        roleDao.insert(role);
	        user1.addRole(role);
	        user2.addRole(role);
	        //取得rolePk
	        Long rolePk = role.getRolePk();
	        //新增角色菜單權限
			roleDao.insertRoleMenuItemPk(menuItemPk, rolePk);
	        //新增user
	        userDao.insert(user1);
	        userDao.insert(user2);
	        //取得userPk
	        List<String> userPk = new ArrayList<String>();
	        userPk.add(user1.getUserPk().toString());
	        userPk.add(user2.getUserPk().toString());
			//新增角色權限
			roleDao.insertRoleUser(userPk, rolePk);
			/* 放行功能
	        TempUser tempUser1 = new TempUser();
	        TempUser tempUser2 = new TempUser();
	        tempUser1.setConfirmStatus(null);//放行狀態 null: 待放行 Y: 放行 N: 退回
	        tempUser2.setConfirmStatus(null);//放行狀態 null: 待放行 Y: 放行 N: 退回
	        tempUser1.setRecordStatus(TempUser.USER_RECORD_SATAUS_ADD_MODE);//交易紀錄狀態 -新增
	        tempUser2.setRecordStatus(TempUser.USER_RECORD_SATAUS_ADD_MODE);//交易紀錄狀態 -新增
	        tempUser1.setUser(user1);
	        tempUser1.setConfirmUserPk(user2.getUserPk());//Admin1建立的帳號要admin2放行過才能使用
	        tempUser2.setUser(user2);
	        userTempDao.insertTempUser(tempUser1);
	        userTempDao.insertTempUser(tempUser2);
	        */
		}

		
		//新增券商同時，新增一筆券商流程設定資料
		ConfirmRule confirmRule = new ConfirmRule();
		confirmRule.setGroup(group);
		confirmRule.setConfirmCount(1);
		confirmRule.setCheckCount(1);
		confirmRule.setConfirmType(0);//放行認證方式 預設為帳號密碼
		confirmRule.setEnabled(true);
		confirmRule.setUpdatedDate(group.getUpdatedDate());
		confirmRule.setUpdatedBy(group.getUpdatedBy());
		confirmRule.setCreatedBy(group.getCreatedBy());
		confirmRule.setCreatedDate(group.getCreatedDate());
		if(insertCount2 > 0){
			return confirmRuleDao.insertConfirmRule(confirmRule);
		}
		return 0;
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.feib.stms.service.GroupService#updateGroup(com.feib.stms.model.Group)
	 */
	public int updateGroup(Group group) {
		//去資料庫查詢該筆group
		Group dbGroup = groupDao.getByGroupPk(group.getGroupPk());
		if(group != null){
			dbGroup.setGroupNo(group.getGroupNo());
			dbGroup.setGroupName(group.getGroupName());
			dbGroup.setUbm(group.getUbm());
			dbGroup.setGroupAddress(group.getGroupAddress());
			dbGroup.setContactName(group.getContactName());
			dbGroup.setContactEmail(group.getContactEmail());
			dbGroup.setContactTelno(group.getContactTelno());
			dbGroup.setContactCellno(group.getContactCellno());
			dbGroup.setGroupNote(group.getGroupNote());
		}
		return groupDao.update(dbGroup);
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.feib.stms.service.GroupService#countGroupNo(java.lang.Long, java.lang.String)
	 */
	public int countGroupNo(Long groupPk, String groupNo) {
		return groupDao.countGroupNo(groupPk, groupNo);
	}
	/*
	 * (non-Javadoc)
	 * @see com.feib.stms.service.GroupService#countGroupNo(java.lang.String)
	 */
	public int countGroupNo(String groupNo) {
		return groupDao.countGroupNo(groupNo);
	}

	public PaginatedList<Group> queryByGroupExcludeBank(Group group,
			PaginatedList<Group> paginatedList) {
		return groupDao.queryForPaginatedListByGroupExcludeBank(group, paginatedList);
	}

	public List<Group> findAllGroup() {
		return groupDao.queryAllGroup();
	}

	public Group getByGroupNo(String groupNo) {
		return groupDao.getByGroupNo(groupNo);
	}

}
